package com.metrology.common.session;

import java.util.HashMap;
import java.util.Map;

public class WebUserUtil {
	private final static ThreadLocal<Map<String, String>> THREAD_INFO = new ThreadLocal<Map<String, String>>();
	public final static Long DEFAULT_USER_ID = 1L;
	public final static String DEFAULT_USER_TYPE = "anonymous";

	public final static String USER_ID = "userId";
	public final static String USER_TYPE = "userType";



	/**
	 * 
	 * getUserInfo
	 * 
	 * @方法作用 将用户常用的信息保存到线程级别的Map对象。
	 * 
	 * @return
	 * 
	 *         Map<String,String>
	 * @exception
	 */
	public static Map<String, String> getUserInfo() {
		Map<String, String> userInfo = (Map<String, String>) THREAD_INFO.get();
		if (userInfo == null) {
			userInfo = new HashMap<String, String>();
			synchronized (THREAD_INFO) {
				THREAD_INFO.set(userInfo);
			}
		}
		return userInfo;
	}

	public static void addInfo(String key, String value) {
		Map<String, String> userInfo = getUserInfo();
		userInfo.put(key, value);
	}

	/**
	 * 
	 * getUserId
	 * 
	 * @方法作用 获取用户的ID。默认为 admin
	 * 
	 * @return
	 * 
	 *         String
	 * @exception
	 */
	public static Long getUserId() {
		String userType = WebUserUtil.getInfo(WebUserUtil.USER_TYPE);
		if (userType == null) {
			return DEFAULT_USER_ID;
		}
		Map<String, String> userInfo = getUserInfo();
		if (userInfo == null || userInfo.get(WebUserUtil.USER_ID) == null) {
			return DEFAULT_USER_ID;
		} else {
			return Long.parseLong(userInfo.get(WebUserUtil.USER_ID));
		}
	}

	public static String getUserType() {
		String userType = WebUserUtil.getInfo(WebUserUtil.USER_TYPE);
		if (userType == null) {
			return DEFAULT_USER_TYPE;
		}
		return userType;
	}

	/**
	 * 
	 * destroy
	 * 
	 * @方法作用 删除当前线程的所有的数据。
	 * 
	 * 
	 *       void
	 * @exception
	 */
	public static synchronized void destroy() {
		THREAD_INFO.remove();
	}

	public static String getInfo(String key) {
		Map<String, String> userInfo = getUserInfo();
		if (userInfo == null) {
			return null;
		} else {
			return userInfo.get(key);
		}
	}

	public static Long getIdInfo(String key) {
		String result = getInfo(key);
		if (result == null) {
			return null;
		} else {
			return Long.parseLong(result);
		}
	}

}
